package com.mgq.netty.chat.handler;

import com.mgq.netty.chat.message.GroupJoinRequestMessage;
import com.mgq.netty.chat.message.GroupJoinResponseMessage;
import com.mgq.netty.chat.session.Group;
import com.mgq.netty.chat.session.GroupSession;
import com.mgq.netty.chat.session.GroupSessionFactory;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * @author MaGuangQi
 * @description
 * @date 2021-12-08 21:26
 **/
@ChannelHandler.Sharable
public class GroupJoinRequestMessageHandler extends SimpleChannelInboundHandler<GroupJoinRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, GroupJoinRequestMessage msg) throws Exception {
        String groupName = msg.getGroupName();
        String username = msg.getUsername();
        GroupSession groupSession = GroupSessionFactory.getGroupSession();
        Group group = groupSession.joinMember(groupName, username);
        if (group == null) {
            ctx.writeAndFlush(new GroupJoinResponseMessage(false, "组不存在"));
        } else {
            //
            ctx.writeAndFlush(new GroupJoinResponseMessage(true, "加入成功"));
            groupSession.joinMember(groupName, username);
            //广播
            groupSession.getMembersChannel(groupName).forEach(channel -> {
                channel.writeAndFlush(new GroupJoinResponseMessage(true, username + "加入群聊"));
            });
        }
    }
}
